import { useIntl } from '@umijs/max';
import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts/core';
import React from 'react';
import { fitChartSize, formatPower } from '../utils/tools';

// 定义数据类型
export interface StationChargeHistoryData {
  stationId: number;
  totalChargeEnergy: number;
  totalDischargeEnergy: number;
  stationName: string;
}

// 定义组件属性类型
interface ChargeDischargeRankingProps {
  data: StationChargeHistoryData[];
}

// 创建组件
const ChargeDischargeRanking: React.FC<ChargeDischargeRankingProps> = ({ data }) => {
  const intl = useIntl();
  // 对数据进行排序，从大到小
  const sortedData = data.sort((a, b) => b.totalChargeEnergy - a.totalChargeEnergy);
  // 提取排序后的数据
  const stationNames = sortedData.map((item) => item.stationName);
  const totalChargeEnergy = sortedData.map((item) =>
    parseFloat(formatPower(item.totalChargeEnergy, false, 'GWh').value),
  );
  const totalDischargeEnergy = sortedData.map((item) =>
    parseFloat(formatPower(item.totalDischargeEnergy, false, 'GWh').value),
  );

  // 计算最大值和最小值
  const maxChargeEnergy = Math.max(...totalChargeEnergy);
  const maxDischargeEnergy = Math.max(...totalDischargeEnergy);
  const maxEnergy = Math.ceil(Math.max(maxChargeEnergy, maxDischargeEnergy)); // 向上取整
  const minEnergy = 0; // 如果数据可能包含负值，可以调整这个值

  // 计算合理的刻度间隔
  const interval = Math.ceil(maxEnergy / 5);

  // 配置 ECharts 选项
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'none',
      },
      backgroundColor: 'rgba(3, 25, 54, 0.7)', // 设置背景颜色和透明度
      borderColor: '#4c8fce', // 设置边框颜色
      borderWidth: 1, // 设置边框宽度
      textStyle: {
        color: '#C4D4F1', // 设置文字颜色
        fontSize: fitChartSize(12),
      },
      formatter: function (params: any) {
        const charge = params.find(
          (param: any) => param.seriesName === intl.formatMessage({ id: 'bigdata.charge' }),
        );
        const discharge = params.find(
          (param: any) => param.seriesName === intl.formatMessage({ id: 'bigdata.discharge' }),
        );
        const chargeValue = `${formatPower(charge.value * 1000000, false, 'GWh').value} GWh`;
        const dischargeValue = `${formatPower(discharge.value * 1000000, false, 'GWh').value} GWh`;
        return `
          ${intl.formatMessage({ id: 'bigdata.charge' })}: ${chargeValue}<br/>
          ${intl.formatMessage({ id: 'bigdata.discharge' })}: ${dischargeValue}
        `;
      },
    },
    legend: {
      data: [
        {
          name: intl.formatMessage({ id: 'bigdata.charge' }),
          icon: 'circle',
          itemStyle: { color: '#56D433' },
        },
        {
          name: intl.formatMessage({ id: 'bigdata.discharge' }),
          icon: 'circle',
          itemStyle: { color: '#1A6CFE' },
        },
      ],
      icon: 'circle',
      itemWidth: fitChartSize(12),
      itemHeight: fitChartSize(12),
      textStyle: {
        color: '#77A5F1',
        fontSize: fitChartSize(12),
      },
      top: '-2%',
      right: 'left',
    },
    grid: {
      left: '3%',
      right: '3%',
      bottom: '15%',
      top: '15%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01],
      show: true,
      splitLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
      },
      axisLabel: {
        color: '#77a5f1',
        fontSize: fitChartSize(12),
        formatter: function (value: number) {
          // 确保显示整数
          return value.toFixed(0);
        },
      },
      min: minEnergy,
      max: maxEnergy,
      interval: interval, // 设置合理的刻度间隔
    },
    yAxis: {
      type: 'category',
      data: stationNames,
      splitLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
      },
      axisLabel: {
        width: 58, // 限制宽度为 58px
        overflow: 'truncate', // 截断文本并显示省略号
        rich: {
          alignLeft: {
            width: 58,
            align: 'left',
            padding: [0, 0, 0, -5], // 通过负的 padding 左移文字
          },
        },
        formatter: function (value: string) {
          if (value.length > 5) {
            return `{alignLeft|${value.slice(0, 4)}...}`;
          }
          return `{alignLeft|${value}}`;
        },
        color: '#77a5f1',
      },
      inverse: true,
    },
    series: [
      {
        name: intl.formatMessage({ id: 'bigdata.charge' }),
        type: 'bar',
        barWidth: 8, // 设置条形图宽度
        barMinHeight: 10,
        barGap: '0%', // 设置不同系列之间的间隔为0
        barCategoryGap: '50%', // 设置同一系列内部的间隙
        itemStyle: {
          normal: {
            barBorderRadius: [0, 6, 6, 0],
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#56d433' },
              { offset: 1, color: '#fffceb' },
            ]),
          },
          emphasis: {
            // 取消 hover 时的颜色
            color: 'none',
            // 或者直接不设置 color 属性
            // 注意，如果设置为 undefined，可能会被识别为有效值，导致颜色重置
          },
          zlevel: 9,
        },
        data: totalChargeEnergy,
        label: {
          show: false,
          position: 'right', // 在条形图右侧显示
          formatter: (params: any) => {
            return `充: ${formatPower(params.value * 1000000, false, 'GWh').value} GWh`;
          },
          color: '#C4D4F1', // 设置文本颜色
          fontSize: fitChartSize(11.5),
        },
      },
      {
        name: intl.formatMessage({ id: 'bigdata.discharge' }),
        type: 'bar',
        barWidth: 8, // 设置条形图宽度
        barMinHeight: 10,
        barGap: '0%', // 设置不同系列之间的间隔为0
        barCategoryGap: '50%', // 设置同一系列内部的间隙
        itemStyle: {
          normal: {
            barBorderRadius: [0, 6, 6, 0],
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#1a6cfe' },
              { offset: 1, color: '#fffceb' },
            ]),
          },
          emphasis: {
            // 取消 hover 时的颜色
            color: 'none',
            // 或者直接不设置 color 属性
            // 注意，如果设置为 undefined，可能会被识别为有效值，导致颜色重置
          },
          zlevel: 9,
        },
        data: totalDischargeEnergy,
        label: {
          show: false,
          position: 'right', // 在条形图右侧显示
          formatter: (params: any) => {
            return `放: ${formatPower(params.value * 1000000, false, 'GWh').value} GWh`;
          },
          color: '#C4D4F1', // 设置文本颜色
          fontSize: fitChartSize(11.5),
        },
      },
      {
        type: 'custom',
        renderItem: (params, api) => {
          const yValue = api.value(1);
          const start = api.coord([0, yValue]);
          const end = api.coord([maxEnergy, yValue]);
          const height = api.size([0, 1])[1] * 0.8; // 调整背景条的高度
          const r = 6; // 圆角半径

          return {
            type: 'group',
            children: [
              {
                type: 'rect',
                shape: {
                  x: start[0],
                  y: start[1] - height / 2,
                  width: end[0] - start[0],
                  height: height,
                  r: [0, r, r, 0], // 设置圆角半径
                },
                style: {
                  fill: '#041736',
                },
              },
            ],
          };
        },
        data: stationNames.map((_, index) => [0, index]),
        z: -1, // 将背景置于最底层
      },
    ],
  };

  return <ReactECharts option={option} style={{ width: '100%', height: fitChartSize(185) }} />;
};

export default ChargeDischargeRanking;
